using FluentValidation;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Specifications;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Interface;

namespace Zhaoxi.Zhihu.UseCases.Answers.Command;

public record DeleteAnswerLikeCommand(int AnswerId) : ICommand<Result>;

public class DeleteAnswerLikeCommandValidator : AbstractValidator<DeleteAnswerLikeCommand>
{
    public DeleteAnswerLikeCommandValidator()
    {
        RuleFor(command =>command. AnswerId).GreaterThan(0);
    }
}

public class DeleteAnswerLikeCommandHandler(IAnswerRepositoy answers, IUser user): ICommandHandler<DeleteAnswerLikeCommand, Result>
{
    public async Task<Result> Handle(DeleteAnswerLikeCommand request, CancellationToken cancellationToken)
    {
        var spec = new AnswerByIdWithLikeByUserIdSpec(request.AnswerId, user.Id!.Value);
        var answer = await answers.GetAnswerByIdWithLikeByUserIdAsync(spec, cancellationToken);
        if (answer == null) return Result.NotFound("回答不存在");
        
        answer.RemoveLike(user.Id!.Value);
        await answers.SaveChangesAsync(cancellationToken);
        return Result.Success();
    }
}